package com.cb.web.wasf.tag;

import java.io.IOException;
import java.io.StringWriter;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyTagSupport;
import javax.servlet.jsp.tagext.TryCatchFinally;

/**
 * @author CBO
 */
public class DefineFragmentTag extends BodyTagSupport implements TryCatchFinally {

    private String name;

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public int doStartTag() throws JspException {
        return EVAL_BODY_BUFFERED;
    }

    @Override
    public int doAfterBody() throws JspException {
        return SKIP_BODY;
    }

    @Override
    public int doEndTag() throws JspException {
        try {
            StringWriter sw = new StringWriter();
            getBodyContent().writeOut(sw);
            UseTemplateTag parent = (UseTemplateTag) findAncestorWithClass(this, UseTemplateTag.class);
            if (parent == null) {
                throw new JspException("PageFragmentTag must be enclosed in PageTag");
            } else {
                parent.putFragment(this.name, sw.toString());
            }
        } catch (IOException ioe) {
            throw new JspException(ioe);
        }
        return EVAL_PAGE;
    }

    @Override
    public void doCatch(Throwable throwable) throws Throwable {
        throw throwable;
    }

    @Override
    public void doFinally() {
        this.name = null;
    }
}
